/**
 * 埋点数据本地存储工具
 * @author lhx
 */

import AsyncStorage from '@react-native-async-storage/async-storage';
import { TrackingEvent, StoredTrackingData, TrackingConfig } from '../types/trackingTypes';

class TrackingStorageLhx {
  private static readonly STORAGE_KEY = 'tracking_data_lhx';
  private static readonly MAX_EVENTS = 1000; // 最大存储事件数
  private static readonly CLEANUP_THRESHOLD = 800; // 清理阈值

  /**
   * 获取存储的埋点数据
   */
  static async getStoredData(): Promise<StoredTrackingData | null> {
    try {
      const data = await AsyncStorage.getItem(this.STORAGE_KEY);
      if (!data) return null;
      
      const parsedData: StoredTrackingData = JSON.parse(data);
      
      // 验证数据完整性
      if (!this.validateStoredData(parsedData)) {
        console.warn('[TrackingStorageLhx] Invalid stored data, clearing storage');
        await this.clearStorage();
        return null;
      }
      
      return parsedData;
    } catch (error) {
      console.error('[TrackingStorageLhx] Error getting stored data:', error);
      return null;
    }
  }

  /**
   * 保存埋点数据
   */
  static async saveData(data: StoredTrackingData): Promise<boolean> {
    try {
      // 检查是否需要清理旧数据
      if (data.events.length > this.CLEANUP_THRESHOLD) {
        data.events = this.cleanupOldEvents(data.events);
      }
      
      await AsyncStorage.setItem(this.STORAGE_KEY, JSON.stringify(data));
      return true;
    } catch (error) {
      console.error('[TrackingStorageLhx] Error saving data:', error);
      return false;
    }
  }

  /**
   * 添加新事件到存储
   */
  static async addEvent(event: TrackingEvent): Promise<boolean> {
    try {
      const existingData = await this.getStoredData();
      
      if (!existingData) {
        // 如果没有现有数据，创建新的存储结构
        const newData: StoredTrackingData = {
          events: [event],
          session: {
            sessionId: event.context.sessionId,
            startTime: Date.now(),
            userId: event.context.userId
          },
          config: this.getDefaultConfig(),
          lastCleanupTime: Date.now()
        };
        return await this.saveData(newData);
      }
      
      // 添加新事件
      existingData.events.push(event);
      return await this.saveData(existingData);
    } catch (error) {
      console.error('[TrackingStorageLhx] Error adding event:', error);
      return false;
    }
  }

  /**
   * 批量添加事件
   */
  static async addEvents(events: TrackingEvent[]): Promise<boolean> {
    try {
      const existingData = await this.getStoredData();
      
      if (!existingData) {
        const newData: StoredTrackingData = {
          events: events,
          session: {
            sessionId: events[0]?.context.sessionId || '',
            startTime: Date.now(),
            userId: events[0]?.context.userId
          },
          config: this.getDefaultConfig(),
          lastCleanupTime: Date.now()
        };
        return await this.saveData(newData);
      }
      
      existingData.events.push(...events);
      return await this.saveData(existingData);
    } catch (error) {
      console.error('[TrackingStorageLhx] Error adding events:', error);
      return false;
    }
  }

  /**
   * 获取未上传的事件
   */
  static async getUnuploadedEvents(): Promise<TrackingEvent[]> {
    try {
      const data = await this.getStoredData();
      if (!data) return [];
      
      return data.events.filter(event => !event.uploaded);
    } catch (error) {
      console.error('[TrackingStorageLhx] Error getting unuploaded events:', error);
      return [];
    }
  }

  /**
   * 标记事件为已上传
   */
  static async markEventsAsUploaded(eventIds: string[]): Promise<boolean> {
    try {
      const data = await this.getStoredData();
      if (!data) return false;
      
      data.events = data.events.map(event => {
        if (eventIds.includes(event.id)) {
          return { ...event, uploaded: true };
        }
        return event;
      });
      
      return await this.saveData(data);
    } catch (error) {
      console.error('[TrackingStorageLhx] Error marking events as uploaded:', error);
      return false;
    }
  }

  /**
   * 删除已上传的事件
   */
  static async removeUploadedEvents(): Promise<boolean> {
    try {
      const data = await this.getStoredData();
      if (!data) return true;
      
      data.events = data.events.filter(event => !event.uploaded);
      return await this.saveData(data);
    } catch (error) {
      console.error('[TrackingStorageLhx] Error removing uploaded events:', error);
      return false;
    }
  }

  /**
   * 清空所有存储数据
   */
  static async clearStorage(): Promise<boolean> {
    try {
      await AsyncStorage.removeItem(this.STORAGE_KEY);
      return true;
    } catch (error) {
      console.error('[TrackingStorageLhx] Error clearing storage:', error);
      return false;
    }
  }

  /**
   * 获取存储统计信息
   */
  static async getStorageStats(): Promise<{
    totalEvents: number;
    unuploadedEvents: number;
    storageSize: number;
  }> {
    try {
      const data = await this.getStoredData();
      if (!data) {
        return { totalEvents: 0, unuploadedEvents: 0, storageSize: 0 };
      }
      
      const dataString = JSON.stringify(data);
      const storageSize = new Blob([dataString]).size; // 估算存储大小
      
      return {
        totalEvents: data.events.length,
        unuploadedEvents: data.events.filter(e => !e.uploaded).length,
        storageSize
      };
    } catch (error) {
      console.error('[TrackingStorageLhx] Error getting storage stats:', error);
      return { totalEvents: 0, unuploadedEvents: 0, storageSize: 0 };
    }
  }

  // 私有方法

  /**
   * 验证存储数据的完整性
   */
  private static validateStoredData(data: any): data is StoredTrackingData {
    return (
      data &&
      Array.isArray(data.events) &&
      data.session &&
      typeof data.session.sessionId === 'string' &&
      data.config &&
      typeof data.config.enabled === 'boolean'
    );
  }

  /**
   * 清理旧事件（保留最新的事件）
   */
  private static cleanupOldEvents(events: TrackingEvent[]): TrackingEvent[] {
    // 按时间戳排序，保留最新的事件
    const sortedEvents = events.sort((a, b) => b.timestamp - a.timestamp);
    
    // 优先保留未上传的事件
    const unuploadedEvents = sortedEvents.filter(e => !e.uploaded);
    const uploadedEvents = sortedEvents.filter(e => e.uploaded);
    
    const maxUnuploaded = Math.floor(this.MAX_EVENTS * 0.8); // 80%给未上传事件
    const maxUploaded = this.MAX_EVENTS - maxUnuploaded;
    
    return [
      ...unuploadedEvents.slice(0, maxUnuploaded),
      ...uploadedEvents.slice(0, maxUploaded)
    ];
  }

  /**
   * 获取默认配置
   */
  private static getDefaultConfig(): TrackingConfig {
    return {
      enabled: true,
      batchSize: 20,
      uploadInterval: 30000, // 30秒
      maxRetries: 3,
      endpoint: '/api/tracking',
      debugMode: __DEV__
    };
  }
}

export default TrackingStorageLhx;